package handels

import (
	"coconut-mgmt/cache"
	"coconut-mgmt/models"
	"coconut-mgmt/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
	}
	var tap models.Tap
	err := models.DB.Where("username = ?", username).First(&tap).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
	}
	if tap.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
	}
	redis_key := "login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
	}
	if pkg.Md5Str(password) != tap.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": tap,
		})
	}
}
func List(c *gin.Context) {
	var tap []models.Tap

	redis_key := "/list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&tap)
		jsonData, _ := json.Marshal(tap)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tap)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": tap,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var tap models.Tap
	models.DB.Where("id = ?", id).First(&tap)
	redis_key := "/list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&id)
		jsonData, _ := json.Marshal(id)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &id)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": tap,
	})
}
